package org.sjm.samples.service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.sjm.samples.dao.IExamScoreDAO;
import org.sjm.samples.dao.IExamTestDAO;
import org.sjm.samples.dao.IExamTestTypeDAO;
import org.sjm.samples.dao.ISubjectDAO;
import org.sjm.samples.dao.IUserSubjectDAO;
import org.sjm.samples.model.ExamScore;
import org.sjm.samples.model.ExamScoreVO;
import org.sjm.samples.model.ExamSubjectVO;
import org.sjm.samples.model.ExamTest;
import org.sjm.samples.model.ExamTestType;
import org.sjm.samples.model.ExamTestTypeVO;
import org.sjm.samples.model.ExamTestVO;
import org.sjm.samples.model.ExamUserVO;
import org.sjm.samples.model.Subject;
import org.sjm.samples.model.User;
import org.sjm.samples.model.UserSubject;
import org.sjm.samples.util.TestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class StudentServiceImpl implements IStudentService {

	@Autowired
	private IExamScoreDAO examScoreDAO;
	
	@Autowired
	private IUserSubjectDAO userSubjectDAO;
	
	@Autowired
	private ISubjectDAO subjectDAO;
	
	@Autowired
	private IExamTestTypeDAO examTestTypeDAO;
	
	@Autowired
	private IExamTestDAO examTestDAO;

	@Override
	public List<ExamSubjectVO> getSubjectList(ExamUserVO userVO) {
		List<ExamSubjectVO> resultList = new ArrayList<ExamSubjectVO>();
		Collection<UserSubject> usubs = userSubjectDAO.getUserSubjectsByUserId(userVO.getUserId());
		for(UserSubject usub : usubs){
			ExamSubjectVO subVO = new ExamSubjectVO();
			BeanUtils.copyProperties(usub.getSubject(), subVO);
			
			ExamScore score = examScoreDAO.getScore(userVO.getUserId(), subVO.getSubId());
			if(score != null){
				ExamScoreVO scoreVO = new ExamScoreVO();
				BeanUtils.copyProperties(score, scoreVO);
				
				Calendar startTime = Calendar.getInstance();
				startTime.setTime(scoreVO.getExamTime());
				Calendar currentTime = Calendar.getInstance();
				currentTime.setTime(new Date());
				long startSecond = startTime.getTimeInMillis();
				long currentSecond = currentTime.getTimeInMillis();
				long totalSecond = Long.parseLong(usub.getSubject().getTotalTime()) * 60;
				scoreVO.setRemainingExamTime(totalSecond - (currentSecond - startSecond) / 1000);
				subVO.setScore(scoreVO);
			}
			resultList.add(subVO);
		}
		return resultList;
	}

	@Override
	public ExamScoreVO getScoreById(Integer scoreId) {
		ExamScoreVO vo = examScoreDAO.getScoreById(scoreId);
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
		vo.setExamTimeString(df.format(vo.getExamTime()));
		return vo;
	}

	@Override
	public Map<Long, List<ExamTestVO>> getTestListBySubject(Integer subId, String userId) {
		List<ExamTestType> testTypeList = examTestTypeDAO.FindAllExamTestTypes();
		Map<Integer, Integer> testTypeScoreMap = new HashMap<Integer, Integer>();//所有题型各自的分数
		Map<Integer, List<ExamTestVO>> testListMap = new HashMap<Integer, List<ExamTestVO>>();
		if(testTypeList != null){
			for(ExamTestType testType : testTypeList){
				testTypeScoreMap.put(testType.getId(), testType.getTestTypeScore());
				List<ExamTest> testList = examTestDAO.getTestListBySubAndTestType(subId, testType.getId());
				List<ExamTestVO> testVOList = new ArrayList<ExamTestVO>();
				for(ExamTest test : testList){
					ExamTestVO vo = new ExamTestVO();
					BeanUtils.copyProperties(test, vo);
					
					ExamTestTypeVO testTypeVO = new ExamTestTypeVO();
					BeanUtils.copyProperties(test.getExamTestType(), testTypeVO);
					vo.setExamTestType(testTypeVO);
					testVOList.add(vo);
				}
				testListMap.put(testType.getId(), testVOList);
			}
		}else{
			return null;
		}
		
		Subject subject = subjectDAO.getSubjectById(subId);
		if(subject == null){
			return null;
		}
		
		//Integer totalTestScore = Integer.getInteger(subject.getTotalScore());
		Integer totalTestCount = Integer.getInteger(subject.getTestCount());
		//校验科目总分和总题数是否匹配
/*		if(!TestUtils.checkSubjectScoreAndCount(totalTestScore, totalTestCount, testTypeScoreMap)){
			return null;
		}*/
		
		// 2. 获取各个题型的数量
		Map<Integer, Integer> testTypeCountMap = TestUtils.getTestCountByScore(totalTestCount, testTypeScoreMap);
		
		Map<Long,  List<ExamTestVO>>  resultTestListMap  =  new  HashMap<Long, List<ExamTestVO>>();
		for(Integer key : testTypeCountMap.keySet()){
			Integer count = testTypeCountMap.get(key);
			List<ExamTestVO> testList = testListMap.get(key);
			//3.1 在里面
			List<Integer> randomTestIdList =  TestUtils.getRandomTestIdList(testList, count);
			if(randomTestIdList == null){
				return null;
			}
			
			//根据多个id获取多个题目
			List<ExamTest> randomTestList = examTestDAO.getTestListByIdList(randomTestIdList);
			
			List<ExamTestVO> testVOList = new ArrayList<ExamTestVO>();
			for(ExamTest test : randomTestList){
				ExamTestVO vo = new ExamTestVO();
				BeanUtils.copyProperties(test, vo);
				
				ExamTestTypeVO testTypeVO = new ExamTestTypeVO();
				BeanUtils.copyProperties(test.getExamTestType(), testTypeVO);
				vo.setExamTestType(testTypeVO);
				testVOList.add(vo);
			}
			resultTestListMap.put(Long.valueOf(key), testVOList);
		}
		
		ExamScore score = new ExamScore();
		User user = new User();
		user.setUserId(userId);
		score.setUser(user);
		Subject sub = new Subject();
		sub.setSubId(subId);
		score.setSubject(subject);
		score.setExamTime(new Date());
		
		examScoreDAO.createExamScore(score);
		examScoreDAO.flush();
		return resultTestListMap;
	}

	@Override
	public void calculateScore(List<Integer> answerIds, Map<String, String[]> testMap, String userId,
			Integer subId) {
		Integer score = 0;
		List<ExamTest> randomTestList = examTestDAO.getTestListByIdList(answerIds);
		for(ExamTest test : randomTestList){
			boolean flag = false;
			String type = test.getExamTestType().getTestType();
			String[] answer = testMap.get(String.valueOf(test.getId()));
			if("单选题".equals(type)){
				if(test.getAnswer().equals(answer[0])){
					flag = true;
				}
			}else if("多选题".equals(type)){
				String[] testAnswer = test.getAnswer().split(",");
				if(answer.length == testAnswer.length){
					for(int i = 0; i < answer.length; i++){
						if(testAnswer[i].equals(answer[i])){
							flag = true;
						}else{
							flag = false;
							break;
						}
					}
				}else{
					flag = false;
				}
			}
			
			if(flag){
				score += test.getExamTestType().getTestTypeScore();
			}
		}
		examScoreDAO.editScore(userId, subId, score);
	}
	
}
